<?php

namespace App\Admin\Controllers;

use App\Models\Vendor;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use App\Admin\Tools\VendorPasswordTool;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Controllers\AdminController;

class VendorAdminsController extends AdminController
{
    protected $title = '商户密码管理';
    
    protected function grid()
    {
        $grid = new Grid(new Administrator());
        $grid->model()->where('id', Admin::user()->id);

        $grid->column('username', '账号');
        $grid->column('name', '名称');
        $grid->column('created_at', '创建时间')->display(function () {
        	return $this->created_at->toDatetimeString();
        });
        
        $this->gridTools($grid);
        $grid->disableFilter();
        $grid->disableCreateButton();
        $grid->disableColumnSelector();
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->disableActions();
        $grid->disablePagination();

        return $grid;
    }
    
    protected function gridTools(Grid $grid)
    {
	    $grid->tools(function (Grid\Tools $tools) {
		    $tools->append(new VendorPasswordTool());
	    });
    }
    
    protected function form()
    {
        $form = new Form(new Administrator());

        $form->password('password', '新密码');
        
        $form->tools(function (Form\Tools $tools) {
        	$tools->disableView();
        	$tools->disableDelete();
        });
        
        $form->footer(function (Form\Footer $footer) {
        	$footer->disableViewCheck();
        	$footer->disableCreatingCheck();
        	$footer->disableEditingCheck();
        });
        
        $form->saving(function (Form $form) {
	        // Passowrd for editing mode
	        if (empty($form->password)) {
		        $form->password = $form->model()->getOriginal('password');
	        }
	        // Password for creating mode
	        else {
		        $form->password = bcrypt($form->password);
		        $vendor = Vendor::query()->where('phone', Admin::user()->username)->first();
		        $vendor->update(['initial_code' => 'has been reset']);
	        }
        });
	    
        return $form;
    }
}
